﻿using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using AForge.Imaging.Filters;
using Tesseract;

namespace WindowsFormsApplication1
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void OnLoad(object sender, EventArgs e)
        {
            
        }


        #region 选择文件
        private string SelectPath()
        {
            string path = string.Empty;

            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有文件(*.*)|*.*";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                path = dialog.FileName;
            }

            return path;
        }

        #endregion


        private void button1_Click(object sender, EventArgs e)
        {
            string sImgPath = SelectPath();
            if(sImgPath == "")
            {
                return;
            }

            RecOcr(sImgPath);
        }

        public void RecOcr(string path)
        {
            var bitmap = AForge.Imaging.Image.FromFile(path);

            this.sourcePic.Image = bitmap;

            var image = AForge.Imaging.Image.Clone(bitmap, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            var threshold = new Threshold { ThresholdValue = 130 };

            var greyscaled = Grayscale.CommonAlgorithms.RMY.Apply(image);

            threshold.ApplyInPlace(greyscaled);

            this.processedPic.Image = greyscaled;


            string sTmp = GetText(greyscaled);

            recognizedText.Clear();
            recognizedText.AppendText(sTmp);
        }

        #region 图形文字识别
        /// <summary>
        /// 图形文字识别
        /// </summary>
        /// <param name="Bitmap bitmap"></param>
        /// <returns></returns>
        public string GetText(Bitmap bitmap, bool bDigit = false)
        {
            string sResult = "";
            string defaultList = "";
            defaultList = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.:+";

            try
            {
                string language = "eng";
                string sTessData = Application.StartupPath + "\\tessdata";

                using (var engine = new TesseractEngine(sTessData, language, EngineMode.Default))
                {
                    engine.DefaultPageSegMode = PageSegMode.AutoOnly;

                    engine.SetVariable("chop_enable", "F");
                    engine.SetVariable("enable_new_segsearch", 0);
                    engine.SetVariable("use_new_state_cost", "F");
                    engine.SetVariable("segment_segcost_rating", "F");
                    engine.SetVariable("language_model_ngram_on", 0);
                    engine.SetVariable("textord_force_make_prop_words", "F");
                    engine.SetVariable("edges_max_children_per_outline", 50);

                    engine.SetVariable("tessedit_char_whitelist", defaultList);

                    using (var tmpPage = engine.Process(bitmap))
                    {
                        var result = tmpPage.GetText().ToString().Split('\n').Where(x => !string.IsNullOrEmpty(x)).ToArray();
                        foreach (var item in result)
                        {
                            sResult += item.Trim() + Environment.NewLine;
                        }
                        tmpPage.Dispose();
                    }//end tmpPage
                }//end engine
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            //GC.Collect();
            return sResult;
        }
        #endregion

    }
}
